using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using ChessKit.Common;

namespace ChessKit.Ui
{
  [TemplatePart(Name = "PART_Queen", Type = typeof(Button))]
  [TemplatePart(Name = "PART_Rook", Type = typeof(Button))]
  [TemplatePart(Name = "PART_Bishop", Type = typeof(Button))]
  [TemplatePart(Name = "PART_Knight", Type = typeof(Button))]
  public class PromotionControl : ContentControl, IPromotionControl
  {
    private class PromotionControlProvideer : IPromotionControlProvider
    {
      public IPromotionControl CreateControl(PieceColor color)
      {
        return new PromotionControl {Color = color};
      }
    }
    public static readonly IPromotionControlProvider Factory = new PromotionControlProvideer();
    public event EventHandler ChoiceDone;

    private void OnChoiceDone(EventArgs e)
    {
      EventHandler handler = ChoiceDone;
      if (handler != null) handler(this, e);
    }

    #region ' PromotionChoice Property '

    public static readonly DependencyProperty PromotionChoiceProperty =
      DependencyProperty.Register("PromotionChoice", typeof(PieceType),
      typeof(PromotionControl), new PropertyMetadata(PieceType.Queen));


    public PieceType PromotionChoice
    {
      get { return (PieceType)GetValue(PromotionChoiceProperty); }
      set { SetValue(PromotionChoiceProperty, value); }
    }

    #endregion

    #region ' Color : PieceColor (Dependency Property) '

    public static readonly DependencyProperty ColorProperty =
      DependencyProperty.Register("Color", typeof(PieceColor),
      typeof(PromotionControl), new PropertyMetadata(null));

    public PieceColor Color
    {
      get { return (PieceColor)GetValue(ColorProperty); }
      set { SetValue(ColorProperty, value); }
    }

    #endregion

    static PromotionControl()
    {
      DefaultStyleKeyProperty.OverrideMetadata(typeof(PromotionControl),
        new FrameworkPropertyMetadata(typeof(PromotionControl)));
    }
    public PromotionControl()
    {
      AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(OnClick));
    }

    private void OnClick(object sender, RoutedEventArgs e)
    {
      var button = e.OriginalSource as Button;
      if (button == null) return;
      switch (button.Name)
      {
        case "PART_Queen":
          PromotionChoice = PieceType.Queen;
          break;
        case "PART_Rook":
          PromotionChoice = PieceType.Rook;
          break;
        case "PART_Bishop":
          PromotionChoice = PieceType.Bishop;
          break;
        case "PART_Knight":
          PromotionChoice = PieceType.Knight;
          break;
        default:
          return;
      }
      OnChoiceDone(EventArgs.Empty);
    }
  }
}